﻿// -----------------------------------------------------------------------
// <copyright file="CacheDispenser.cs" company="EPAM Systems">
////Copyright (c) EPAM Systems. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System;

namespace Epam.PhotoGallery.Bussines.CacheManager
{
	using System.Web;
	using System.Collections;
	using System.Collections.Generic;
	using Epam.PhotoGallery.Bussines.Configuration;
	using System.Configuration;

	/// <summary>
	/// TODO: Update summary.
	/// </summary>
	public class CacheDispenser
	{
		/// <summary>
		/// Cache item dictionary
		/// </summary>
		private Dictionary<string, CacheItem> cacheItemDictionary;

		//public Dictionary<string, CacheItem> CacheItemDictionary {}

		/// <summary>
		/// Processes the specified key.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="slide">The slide.</param>
		/// <param name="minCounter">The min counter.</param>
		/// <param name="high">The high.</param>
		/// <param name="normal">The normal.</param>
		/// <param name="low">The low.</param>
		/// <param name="waitingTime">The waiting time.</param>
		/// <returns></returns>
		public string Process(string key, int slide, int minCounter, int high, int normal, int low, int waitingTime)
		{
			string result = null;
			HttpContext.Current.Application.Lock();
			cacheItemDictionary = HttpContext.Current.Application["Dispenser"] as Dictionary<string, CacheItem>;
			HttpContext.Current.Application.UnLock();

			if (this.cacheItemDictionary != null)
			{

				if (this.cacheItemDictionary.ContainsKey(key))
				{
					result = this.cacheItemDictionary[key].Process(minCounter, high, normal, low);
					if (result == null)
					{
						this.cacheItemDictionary.Remove(key);
						//lock (this.cacheItemDictionary)
						//{
						//    CleanYourSelf(waitingTime);
						//}
					}
				}
				else
				{
					this.cacheItemDictionary.Add(key, new CacheItem(DateTime.Now));
				}
			}
			else
			{
				this.cacheItemDictionary = new Dictionary<string, CacheItem>();
				this.cacheItemDictionary.Add(key, new CacheItem(DateTime.Now));
			}
			HttpContext.Current.Application.Lock();
			HttpContext.Current.Application["Dispenser"] = cacheItemDictionary;
			HttpContext.Current.Application.UnLock();
			return result;
		}

		/// <summary>
		/// Cleans your self.
		/// </summary>
		/// <param name="waitingTime">The waiting time.</param>
		private void CleanYourSelf(int waitingTime)
		{
			foreach (var item in this.cacheItemDictionary)
			{

				TimeSpan currentWaitingTime = DateTime.Now - item.Value.TimeLast;
				string key = item.Key;
				if (TimeSpan.FromSeconds(waitingTime) <= currentWaitingTime)
				{
					this.cacheItemDictionary.Remove(key);
				}
			}
		}
	}
}
